<template>
  <div class="system-message-container">
    <div class="message-header">
      <div class="header-title">
        <div class="title-icon">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
        </div>
        <h2>系统消息</h2>
      </div>
      <div class="type-switch-group">
        <div class="left-btns">
          <button :class="{active: currentType === 0}" @click="switchType(0)" class="filter-btn">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <circle cx="12" cy="12" r="10"/>
            </svg>
            未读
          </button>
          <button :class="{active: currentType === 1}" @click="switchType(1)" class="filter-btn">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
            </svg>
            已读
          </button>
          <button :class="{active: currentType === -1}" @click="switchType(-1)" class="filter-btn">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
            </svg>
            全部
          </button>
        </div>
        <div class="right-btns">
          <button v-if="messages.length > 0" class="mark-all-read-btn" @click="handleMarkAllRead" :disabled="loading">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <path d="M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z"/>
            </svg>
            全部已读
          </button>
          <div v-if="loading" class="loading">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="!loading && messages.length === 0" class="empty">
      <div class="empty-icon">
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
        </svg>
      </div>
      <p>暂无系统消息</p>
      <span>您还没有收到任何系统通知</span>
    </div>
    <ul v-else-if="!loading" class="msg-list">
      <li v-for="(item, index) in messages" :key="item.id" 
          class="msg-item" 
          :class="{ 'unread': item.isRead === 0 }"
          :style="{ animationDelay: `${index * 0.1}s` }"
          @click="handleMessageClick(item)">
        <div class="msg-avatar">
          <div class="avatar-icon system-type">
            <svg viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
            </svg>
          </div>
        </div>
        <div class="msg-content">
          <div class="msg-type-row">
            <span class="msg-type-badge system-type">{{ getMessageTypeName(item.messageType) }}</span>
          </div>
          <div class="msg-text">{{ item.content }}</div>
        </div>
        <div class="msg-meta">
          <span class="msg-time">{{ formatTime(item.time) }}</span>
          <div v-if="item.isRead === 0" class="unread-indicator">
            <span class="pulse-ring"></span>
            <span class="unread-dot"></span>
          </div>
        </div>
      </li>
    </ul>
    
    <div v-if="totalPages > 1" class="pagination">
      <button @click="prevPage" :disabled="currentPage === 0" class="pagination-btn">
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
        上一页
      </button>
      <button v-for="p in displayPages" :key="p" 
              :class="{active: currentPage === p - 1}" 
              @click="goToPage(p - 1)"
              class="pagination-btn page-number">{{ p }}</button>
      <button @click="nextPage" :disabled="currentPage >= totalPages - 1" class="pagination-btn">
        下一页
        <svg viewBox="0 0 24 24" fill="currentColor">
          <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
        </svg>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useMessageStore } from '../../stores/message'
import { useUserStore } from '../../stores/user'
import { storeToRefs } from 'pinia'
import { markAllMessagesAsRead } from '../../api/message'
import type { UserMessage } from '../../api/message'

const messageStore = useMessageStore()
const userStore = useUserStore()
const { messages, loading, currentPage, totalPages, totalElements } = storeToRefs(messageStore)

const currentType = ref(-1) // -1: 全部, 0: 未读, 1: 已读
const pageSize = ref(4)

// 计算显示的页码
const displayPages = computed(() => {
  const pages: number[] = []
  const maxDisplay = 5
  let start = Math.max(0, currentPage.value - Math.floor(maxDisplay / 2))
  let end = Math.min(totalPages.value, start + maxDisplay)
  
  if (end - start < maxDisplay) {
    start = Math.max(0, end - maxDisplay)
  }
  
  for (let i = start; i < end; i++) {
    pages.push(i + 1)
  }
  return pages
})

// 切换消息类型
const switchType = async (type: number) => {
  currentType.value = type
  await loadMessages(0)
}

// 加载消息
const loadMessages = async (page: number = 0) => {
  if (!userStore.id) {
    console.error('用户未登录')
    return
  }
  try {
    // messageType = 0 表示系统消息
    await messageStore.fetchMessages(Number(userStore.id), 0, currentType.value, page, pageSize.value)
  } catch (error) {
    console.error('加载消息失败:', error)
  }
}

// 处理消息点击
const handleMessageClick = async (message: UserMessage) => {
  // 如果是未读消息，标记为已读
  if (message.isRead === 0) {
    try {
      await messageStore.markAsRead(message.id)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  // 系统消息暂不跳转
}

// 全部已读按钮事件
const handleMarkAllRead = async () => {
  if (!userStore.id) return
  try {
    await markAllMessagesAsRead(Number(userStore.id))
    await loadMessages(currentPage.value)
  } catch (e) {
    console.error('全部设为已读失败', e)
  }
}

// 分页控制
const prevPage = () => {
  if (currentPage.value > 0) {
    loadMessages(currentPage.value - 1)
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value - 1) {
    loadMessages(currentPage.value + 1)
  }
}

const goToPage = (page: number) => {
  loadMessages(page)
}

// 获取消息类型名称
const getMessageTypeName = (type: string) => {
  switch (type) {
    case 'system': return '系统'
    default: return '消息'
  }
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const backendDate = new Date(timeStr)
  const correctedDate = new Date(backendDate.getTime() - 8 * 60 * 60 * 1000)
  const now = new Date()
  const diff = now.getTime() - correctedDate.getTime()
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return correctedDate.toLocaleDateString() + ' ' + correctedDate.toLocaleTimeString().slice(0, 5)
  }
}

// 页面加载时获取消息
onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.system-message-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  animation: fadeIn 0.6s ease-out;
}

.message-header {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 32px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.title-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  animation: pulse 2s infinite;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.loading {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4ecdc4;
  font-size: 14px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e3f2fd;
  border-top: 2px solid #4ecdc4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.msg-list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 16px;
  flex: 1;
}

.msg-item {
  background: linear-gradient(135deg, #f8fafd 0%, #ffffff 100%);
  border-radius: 16px;
  padding: 20px;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border: 1px solid #f0f4ff;
  box-shadow: 0 2px 8px rgba(78, 205, 196, 0.06);
  animation: slideInLeft 0.5s ease-out;
  animation-fill-mode: both;
}

.msg-item:hover {
  background: linear-gradient(135deg, #f0fff4 0%, #ffffff 100%);
  box-shadow: 0 8px 32px rgba(78, 205, 196, 0.15);
  transform: translateY(-2px);
}

.msg-item.unread {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafd 100%);
  border-left: 4px solid #4ecdc4;
  box-shadow: 0 4px 20px rgba(78, 205, 196, 0.12);
}

.msg-item.unread::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(78, 205, 196, 0.03) 0%, rgba(68, 160, 141, 0.03) 100%);
  border-radius: 16px;
  pointer-events: none;
}

.msg-avatar {
  flex-shrink: 0;
}

.avatar-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  transition: transform 0.3s ease;
}

.avatar-icon:hover {
  transform: scale(1.1);
}

.avatar-icon.system-type {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
}

.avatar-icon svg {
  width: 24px;
  height: 24px;
}

.msg-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.msg-type-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.msg-type-badge {
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  width: fit-content;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.msg-type-badge.system-type {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
}

.msg-text {
  line-height: 1.6;
  text-align: left;
  color: #444;
  font-size: 15px;
}

.msg-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  flex-shrink: 0;
}

.msg-time {
  color: #999;
  font-size: 12px;
  font-weight: 500;
}

.unread-indicator {
  position: relative;
  width: 12px;
  height: 12px;
}

.unread-dot {
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(78, 205, 196, 0.4);
}

.pulse-ring {
  position: absolute;
  top: -4px;
  left: -4px;
  width: 20px;
  height: 20px;
  border: 2px solid #4ecdc4;
  border-radius: 50%;
  animation: pulse 2s cubic-bezier(0.455, 0.03, 0.515, 0.955) infinite;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-top: 80px;
  animation: fadeIn 0.8s ease-out;
}

.empty-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 20px;
  animation: float 3s ease-in-out infinite;
}

.empty-icon svg {
  width: 40px;
  height: 40px;
}

.empty p {
  font-size: 18px;
  font-weight: 600;
  color: #666;
  margin: 0 0 8px 0;
}

.empty span {
  font-size: 14px;
  color: #999;
}

.pagination {
  display: flex;
  gap: 8px;
  margin: 32px 0 0 0;
  justify-content: center;
}

.pagination-btn {
  background: linear-gradient(135deg, #f8fafd 0%, #ffffff 100%);
  border: 1px solid #e0e8f0;
  border-radius: 10px;
  padding: 10px 16px;
  color: #4ecdc4;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 6px;
}

.pagination-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(78, 205, 196, 0.3);
}

.pagination-btn.active {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(78, 205, 196, 0.3);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-btn svg {
  width: 16px;
  height: 16px;
}

.pagination-btn.page-number {
  min-width: 40px;
  justify-content: center;
}

.type-switch-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-btns {
  display: flex;
  gap: 8px;
  align-items: center;
}

.filter-btn {
  background: linear-gradient(135deg, #f8fafd 0%, #ffffff 100%);
  color: #4ecdc4;
  border: 1px solid #e0e8f0;
  border-radius: 12px;
  padding: 10px 18px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  outline: none;
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-btn .btn-icon {
  width: 16px;
  height: 16px;
}

.filter-btn.active {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  color: #fff;
  border-color: #4ecdc4;
  box-shadow: 0 4px 16px rgba(78, 205, 196, 0.3);
  transform: translateY(-1px);
}

.filter-btn:hover:not(:disabled):not(.active) {
  background: linear-gradient(135deg, #e8f8f5 0%, #f3fff7 100%);
  color: #4ecdc4;
  transform: translateY(-1px);
  box-shadow: 0 2px 12px rgba(78, 205, 196, 0.15);
}

.right-btns {
  display: flex;
  align-items: center;
}

.mark-all-read-btn {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  color: #fff;
  border: none;
  border-radius: 12px;
  padding: 10px 18px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  margin-left: 16px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 6px;
}

.mark-all-read-btn .btn-icon {
  width: 16px;
  height: 16px;
}

.mark-all-read-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #44a08d 0%, #396c5c 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(78, 205, 196, 0.4);
}

.mark-all-read-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-6px);
  }
}
</style>
